package online.heycm.codegenerator.common.session;

import online.heycm.codegenerator.common.error.CodeMsg;
import online.heycm.platform.common.entity.constant.Constant;
import online.heycm.platform.common.entity.exception.Assert;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hey
 * @version 1.0
 * @date 2023/12/21 11:19
 */
public class SessionResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        return clazz == Session.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader(Constant.AUTHORIZATION);
        Assert.hasText(token, CodeMsg.INVALID_SESSION);
        Session session = SessionStorage.get(token);
        Assert.notNull(session, CodeMsg.INVALID_SESSION);
        session.setOperateAt(System.currentTimeMillis());
        return session;
    }
}
